package com.mini.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.*;

@Slf4j
public class HttpClientUtil {

    static final int timeOut = 10 * 1000;

    private static CloseableHttpClient httpClient = null;

    private final static Object syncLock = new Object();

    private static void config(HttpRequestBase httpRequestBase) {

        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(timeOut)
                .setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
        httpRequestBase.setConfig(requestConfig);
    }

    /**
     * 获取HttpClient对象
     *
     * @return
     * @author SHANHY
     * @create 2015年12月18日
     */
    public static CloseableHttpClient getHttpClient(String url) {
        String hostname = url.split("/")[2];
        int port = 80;
        if (hostname.contains(":")) {
            String[] arr = hostname.split(":");
            hostname = arr[0];
            port = Integer.parseInt(arr[1]);
        }
        if (httpClient == null) {
            synchronized (syncLock) {
                if (httpClient == null) {
                    httpClient = createHttpClient(200, 40, 100, hostname, port);
                }
            }
        }
        return httpClient;
    }

    /**
     * 创建HttpClient对象
     *
     * @return
     * @author SHANHY
     * @create 2015年12月18日
     */
    public static CloseableHttpClient createHttpClient(int maxTotal,
                                                       int maxPerRoute, int maxRoute, String hostname, int port) {
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
                .getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory
                .getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", plainsf)
                .register("https", sslsf).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
                registry);
        // 将最大连接数增加
        cm.setMaxTotal(maxTotal);
        // 将每个路由基础的连接增加
        cm.setDefaultMaxPerRoute(maxPerRoute);
        HttpHost httpHost = new HttpHost(hostname, port);
        // 将目标主机的最大连接数增加
        cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);

        // 请求重试处理
        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception,
                                        int executionCount, HttpContext context) {
                if (executionCount >= 5) {// 如果已经重试了5次，就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接，那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return false;
                }
                if (exception instanceof UnknownHostException) {// 目标服务器不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {// SSL握手异常
                    return false;
                }

                HttpClientContext clientContext = HttpClientContext
                        .adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 如果请求是幂等的，就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setRetryHandler(httpRequestRetryHandler).build();

        return httpClient;
    }

    private static void setPostParams(HttpPost httpost,
                                      Map<String, Object> params) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    /**
     * POST请求URL获取内容
     *
     * @param url
     * @return
     * @throws IOException
     * @author SHANHY
     * @create 2015年12月18日
     */
    public static String post(String url, Map<String, Object> params) throws IOException {
        long start = System.currentTimeMillis();
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        setPostParams(httppost, params);
        CloseableHttpResponse response = null;
        String result = "";
        try {
            response = getHttpClient(url).execute(httppost,
                    HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("post {} cost: {}ms --> \n{} ,params={}, ex = {}", new Object[]{url , (System.currentTimeMillis() - start), result}, JSON.toJSONString(params), e.getMessage());
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static String post(String url, String string) throws IOException {
        long start = System.currentTimeMillis();
        HttpPost httppost = new HttpPost(url);
        config(httppost);
        setPostString(httppost, string);
        CloseableHttpResponse response = null;
        String result = "";
        try {
            response = getHttpClient(url).execute(httppost,
                    HttpClientContext.create());
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity);
                }
            }
            log.info("post {} cost: {}ms --> \n{}", new Object[]{url + "?" + string, (System.currentTimeMillis() - start), result});
            return result;
        } catch (Exception e) {
            log.error("post {} cost: {}ms --> \n{}", new Object[]{url + "?" + string, (System.currentTimeMillis() - start), result});
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String post(String url, Map<String, String> headers, Map<String, String> params, String requestBody) throws IOException {
        long start = System.currentTimeMillis();

        if (requestBody == null) {
            requestBody = "";
        }

        if (params == null) {
            params = new HashMap<>();
        }
        if (params.isEmpty()) {
            params.put("t", String.valueOf(System.currentTimeMillis()));
        }

        Set<String> keySet = params.keySet();
        NameValuePair[] nvps = new NameValuePair[keySet.size()];
        int i = 0;
        for (String key : keySet) {
            nvps[i] = new BasicNameValuePair(key, params.get(key).toString());
            i++;
        }

        RequestBuilder requestBuilder = RequestBuilder.post();
        if (headers != null && !headers.isEmpty()) {
            Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }


        HttpUriRequest httpUriRequest = requestBuilder
                .setUri(url)
                .addParameters(nvps)
                .setEntity(new StringEntity(requestBody, Charset.forName("utf-8")))
                .build();

        CloseableHttpResponse response = null;
        String result = "";
        Integer responseCode=null;
        try {
            response = getHttpClient(url).execute(httpUriRequest,
                    HttpClientContext.create());
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                responseCode = response.getStatusLine().getStatusCode();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity);
                }
            }

            log.info("post {} responseCode={} cost: {}ms --> \n{}", new Object[]{url + "?" + toParam(params, "utf-8") + "&body=" + requestBody, responseCode,(System.currentTimeMillis() - start), result});
            return result;
        } catch (Exception e) {
            log.error("post {} responseCode={} cost: {}ms --> \n{}", new Object[]{url + "?" + toParam(params, "utf-8") + "&body=" + requestBody,responseCode, (System.currentTimeMillis() - start), result});
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static String get(String url, Map<String, String> params) {
        long start = System.currentTimeMillis();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            if (params!=null && !params.isEmpty()) {
                url += "?" + toParam(params, "utf-8");
            }
            HttpGet httpget = new HttpGet(url);
            config(httpget);
            response = getHttpClient(url).execute(httpget,
                    HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("get {} cost: {}ms --> \n{}", new Object[]{url, (System.currentTimeMillis() - start), result});
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String toParam(Map<String, String> params, String encode) throws UnsupportedEncodingException {
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (stringBuilder.length() > 0) {
                stringBuilder.append("&");
            }
            if (encode == null) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
            } else {
                stringBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode));
            }

        }
        return stringBuilder.toString();
    }

    private static void setPostString(HttpPost httpost, String s) {
        httpost.setEntity(new StringEntity(s, Charset.forName("UTF-8")));
    }


    public static String post(String url, String json, int timeout) {
        log.info("url=" + url + ",json=" + json);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = setHttpPostConfig(url, timeout);

        CloseableHttpResponse response = null;
        try {
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setEntity(new StringEntity(json, "UTF-8"));
            response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode == 200) {
                return result;
            }
            log.info("post code={},post result :{}", responseCode, result);
        } catch (Exception e) {
            log.error("post is error {},   url = {}", e, url);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("post is error {},   url = {}", e, url);
            }
        }
        return "";
    }

    private static HttpPost setHttpPostConfig(String url, int timeout) {
        HttpPost post = new HttpPost(url);
        RequestConfig config = RequestConfig.custom()
                .setConnectionRequestTimeout(timeout)
                .setConnectTimeout(timeout).setRedirectsEnabled(true)
                .setSocketTimeout(timeout).build();
        post.setConfig(config);
        return post;
    }

}
